import PropTypes from 'prop-types'
import React, { memo, useEffect, useRef } from 'react'
import IndicatorWrapper from './style'

const Indicator = memo((props) => {
  
  const {currIndex} = props
  // 定义一个ref
  const indicRef = useRef()
  
  useEffect(() => {
    const selectEl = indicRef.current.children[currIndex]
    const itemSet = selectEl.offsetLeft
    const itemWid = selectEl.clientWidth
    // content的宽度,总共宽度(包含隐藏的)
    const contWidth = indicRef.current.clientWidth
    const contScrol = indicRef.current.scrollWidth
    let offS = itemSet + itemWid * 0.5 - contWidth * 0.5

    // 让图片挨近左边
    if(offS<0) offS = 0
    let totalOffS = contScrol - contWidth
    if(offS>totalOffS) offS = totalOffS  

    // 修改item的translate
    indicRef.current.style.transform = `translate(${-offS}px)`

    // console.log(itemSet,itemWid,offS,contScrol,contWidth);
  },[currIndex])
  return (
    <IndicatorWrapper>
      <div className="content" ref={indicRef}>
        {props.children}
      </div>
    </IndicatorWrapper>
  )
})

Indicator.propTypes = {
  currIndex: PropTypes.number
}

export default Indicator